package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.entity.Permissions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter{

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求的路径
        String requestURI = request.getRequestURI();
        //log.info("拦截到请求：{}",requestURI);
        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        //判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        //如果不需要处理，则直接放行
        if(check){
            filterChain.doFilter(request,response);
            log.info("处理完毕...");
            //逻辑处理完毕之后，移除ThreadLocal中存储的数据
            BaseContext.remove();
            return;
        }

        //若登陆就放行
        if(request.getSession().getAttribute("employee") != null){
            List<Permissions> permissions = (List<Permissions>) request.getSession().getAttribute("permissions");

            String requestMethod = request.getMethod();
            // 不匹配，说明没有访问的权限
            if (!isMatch(requestURI, requestMethod, permissions)) {
                response.getWriter().write(JSON.toJSONString(R.error("NO_PERMISSION")));
                return;
            }
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId (empId);
            filterChain.doFilter(request,response);

            log.info("处理完毕...");
            //逻辑处理完毕之后，移除ThreadLocal中存储的数据
            BaseContext.remove();
            return;
        }
        //移动端是否登陆
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登陆，用户id为：{}",request.getSession().getAttribute("user"));

            //通过ThreadLocal保存当前登陆用户的id
            Long empId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(empId);

            //放行
            filterChain.doFilter(request, response);

            log.info("处理完毕...");
            //逻辑处理完毕之后，移除ThreadLocal中存储的数据
            BaseContext.remove();
            return;
        }
       // log.info("用户未登录");
        //响应数据到前端页面
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }
    // 提取的isMatch方法
    private boolean isMatch(String requestURI, String requestMethod, List<Permissions> permissions) {
        if (permissions != null) {
            for (Permissions permission : permissions) {
                String methodType = permission.getMethodType();
                String url = permission.getUrl();
                boolean match = PATH_MATCHER.match(url, requestURI);
                if (match && PATH_MATCHER.match(methodType, requestMethod)) {
                    return true;
                }
            }
        }
        return false;
    }
    //路径匹配器，支持通配符
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}